# -*- coding: UTF-8 -*-
# __author__ = '10459'
from threading import Thread
from app import mail
from flask_mail import Message
from flask import current_app, render_template


# 测试代码,新的不用文本body
# def send_mail():
#     msg=Message(subject='测试ta妹妹',sender='1045933569@qq.com',body='test',recipients=['2412187413@qq.com'])
#     mail.send(msg)
def send_async_email(app, msg):
    with app.app_context():
        try:
            mail.send(msg)
        except Exception as e:
            print(e)


def send_mail(to, subject, template, **kwargs):
    msg = Message('[鱼书]' + ' ' + subject, sender=current_app.config['MAIL_USERNAME'], recipients=[to])
    msg.html = render_template(template, **kwargs)
    # 启动一个线程，然后将参数msg传递进去，注意用args传递参数,current_app有值，因为视图函数有请求
    #拿到真实核心对象，而不是代理对象,app=<flask"app">
    app = current_app._get_current_object()
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
